<?php

namespace app\admin\controller\wu;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\Exception;
use think\Session;


//use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

/**
 * 工序管理
 *
 * @icon fa fa-circle-o
 */
class Procedure extends Backend
{

    /**
     * Procedure模型对象
     * @var \app\admin\model\wu\Procedure
     */
    protected $model = null;

    const PRODPEC_ID = "__productspecid__";

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wu\Procedure;

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        $productspec_id = 0;
        $url = $_SERVER['HTTP_REFERER'];
        $productspecname = "";
        if (false !== strpos($url, '/ids/')) {
            $urls = explode('?', $url);
            $url = $urls[0];
            $urls = explode('/', $url);
            $size = count($urls);
            $productspec_id = $urls[$size - 1];
            Session::set(self::PRODPEC_ID, $productspec_id);

            $productspec = \app\admin\model\wu\Productspec::get($productspec_id);
            if ($productspec) {
                $productspecname = $productspec->name;
            }
        } else {
            Session::set(self::PRODPEC_ID, 0);
        }

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if ($productspec_id > 0) {
                $total = $this->model
                    ->with(['productspec'])
                    ->where($where)
                    ->where('productspec_id', $productspec_id)
//                    ->order($sort, $order)
                    ->order('procedure.order', 'ASC')
                    ->count();

                $list = $this->model
                    ->with(['productspec'])
                    ->where($where)
                    ->where('productspec_id', $productspec_id)
//                    ->order($sort, $order)
                    ->order('procedure.order', 'ASC')
                    ->limit($offset, $limit)
                    ->select();
            } else {
                $total = $this->model
                    ->with(['productspec'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['productspec'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        $this->view->assign("productspecname", $productspecname);
        $this->view->assign("productspec_id", $productspec_id);

        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $order = intval($params['order']);
                if ($order == 1) {
                    //首个工序必需是
                    //第一個工序必須”01 到廠” 或”04 半成品庫存” 或”06 白刀庫存”
                    //最後一個工序，必須或”04 半成品庫存” 或”06 白刀庫存” 或”10 回公司入庫”
                    if ($params['name'] !== "到廠" || $params['name'] !== "半成品庫存" || $params['name'] !== "白刀庫存") {
                        $this->error(__('第一個工序必須是"到廠"或"半成品庫存"或"白刀庫存"'));
                    }
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $productspec_id = Session::get(self::PRODPEC_ID);
        $this->view->assign("productspec_id", $productspec_id);
        return $this->view->fetch();
    }


}
